import { _decorator, Component, instantiate, Label, Node, Prefab, v3 } from 'cc';
import { Enemy } from './ctrl/Enemy';
const { ccclass, property } = _decorator;

@ccclass('MoonGame')
export class MoonGame extends Component {

    @property([Prefab])
    groupPrefabs: Prefab[] = []

    public enemySet: Node[]

    private score: number;

    private scoreLabel: Label

    private player: Node

    protected onLoad(): void {
        this.enemySet = []
       
        this.score = 0;
        this.scoreLabel = this.node.getChildByPath("Score").getComponent(Label)
        this.scoreLabel.string = "" + this.score;

        this.player = this.node.getChildByPath("Player")
    }

    protected start(): void {
        this.genRandomGroup()
    }

    public addScore() {
        this.score++
        this.scoreLabel.string = "11" + this.score;
    }

    removeEnemy(enemy: Node) {
        let index = this.enemySet.indexOf(enemy)
        if (index >= 0) {
            this.enemySet.splice(index, 1)
        }
    }


    private genRandomGroup() {
        console.info('gen random')
        let groupType = Math.floor(Math.random() * this.groupPrefabs.length);
        if (groupType >= this.groupPrefabs.length) {
            groupType = this.groupPrefabs.length - 1;
        }
        console.info('groupTupe', groupType)
        let group = instantiate(this.groupPrefabs[groupType])
        this.node.addChild(group)
        group.children.forEach(enemy => {
            enemy.getComponent(Enemy).init(this, this.player)
            this.enemySet.push(enemy)
        })
        group.setPosition(v3((Math.random() - 0.5) * 200, (Math.random()) * 100 + 500, 0))
        this.scheduleOnce(() => {
            this.genRandomGroup()
        }, Math.random() * 3 + 2);
    }

}

